package jsyf.oa.web.attach;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.OSS;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import jsyf.com.service.TAttachmentService;
import jsyf.com.util.*;
import jsyf.oa.entity.attach.AttachmentEntity;
import jsyf.oa.facade.attach.AttachFacade;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 * Created by Administrator on 2017/12/7 0007.
 */
@Api(value = "附件上传下载接口", description = "附件上传下载接口")
@Controller
@RequestMapping("/attach")
public class AttachController {
    @Resource
    private AttachFacade attachFacade;

    public static String generateGUID(String filename) {
        String filetype = filename.substring(filename.lastIndexOf("."));
        filename = UUID.randomUUID().toString().replace("-", "");
        return filename + filetype;
    }

    /**
     * @description: 附件上传
     * @author: @崔程鵬 @cuichengpeng
     * @creat: 16:27  2017/10/25
     * @since: V1.0.0
     * @see jsyf.oa.web
     */

    @ResponseBody
    @Transactional(rollbackFor = Exception.class)
    @RequestMapping(value ="/uploadFile.json",method = RequestMethod.POST)
    public void uploadFile(HttpServletRequest request, HttpServletResponse response, String fileType) {
        String filename = null;
        try {
            MultipartFile mf = RequestUtils.getUploadFile(request);
            if (mf == null || mf.isEmpty()) {
                ResponseUtils.putJsonFailureResponse(response, "未指定上传文件");
                return;
            }
            filename = generateGUID(mf.getOriginalFilename());
            InputStream inputStream = mf.getInputStream();
            String url = OssClient.uploadFileToOSS(inputStream, filename);
            //往数据库中存数据
            String name = mf.getOriginalFilename();
            String extension = getExtName(mf.getOriginalFilename());
            String size = String.valueOf(mf.getSize());

            String id = attachFacade.save(url, name, extension, size);
            //返回数据给前台
            JSONObject objResult = new JSONObject();
            objResult.put("id", id);
            objResult.put("name", name);
            objResult.put("url", url);
            String record = JSON.toJSONString(objResult);
            ResponseUtils.putJsonResponse(response, record);
        } catch (Exception e) {
            e.printStackTrace();
            ResponseUtils.putTextResponse(response, "文件上传出错！");
        }
    }

    //获取后缀名
    public String getExtName(String filename) {
        if (StringUtils.isBlank(filename)) {
            return null;
        }
        int i = filename.indexOf(".");
        if (i >= 0) {
            return filename.substring(i + 1).trim().toLowerCase();
        }
        return null;
    }

    /**
     * @description: umEditor图片上传
     * @author: @崔程鵬 @cuichengpeng
     * @creat: 10:52  2017/12/5 0005
     * @since: V1.0.0
     * @see jsyf.oa.web
     */
    @ResponseBody
    @Transactional(rollbackFor = Exception.class)
    @RequestMapping(value = "/multiFileUpload.json")
    public void imageUpload(HttpServletRequest request, HttpServletResponse response, HttpSession session) {
        try {
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            // 获取文件
            MultipartFile file = multipartRequest.getFile("upfile");
            if (!file.isEmpty()) {
                String result = "";
                String filename = generateGUID(file.getOriginalFilename());
                String size = String.valueOf(file.getSize());
                String extension = getExtName(file.getOriginalFilename());
                InputStream inputStream = file.getInputStream();
                String url = OssClient.uploadFileToOSS(inputStream, filename);
                result = "{\"name\":\"" + filename
                        + "\", \"originalName\": \"" + filename
                        + "\", \"size\": " + size
                        + ", \"state\": \"SUCCESS\", " +
                        "\"type\": \"" + extension
                        + "\", \"url\": \"" + url + "\"}";
                result = result.replaceAll("\\\\", "\\\\");
                session.setAttribute("result", result);
                response.getWriter().print(result);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @ResponseBody
    @Transactional(rollbackFor = Exception.class)
    @RequestMapping(value = "/getdataInfo.json")
    public void getdataInfo(HttpServletRequest request, HttpServletResponse response, HttpSession session, String callbackparam) {
        String result = (String) session.getAttribute("result");
        try {
            response.getWriter().print(callbackparam + "(" + result + ")");
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * @description: 下载附件
     * @author: @崔程鵬 @cuichengpeng
     * @creat: 10:32  2017/11/14 0014
     * @since: V1.0.0
     * @see jsyf.oa.web
     */
    @ApiOperation(
            value = "下載文件方法",
            notes = "下載文件方法",
            httpMethod = "GET",
            produces = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParam(name = "jsonData", value = "", dataType = "String", paramType = "body")
    @RequestMapping("/downloadFile.json")
    public ResponseEntity<byte[]> downloadFile(HttpServletRequest request, HttpServletResponse response, @RequestParam String fileUrl, @RequestParam String fileName) throws Exception {
        byte[] body = null;
        if (fileUrl.contains("group1")) {
            InputStream is = FastDFSClientUtils.download("group1", fileUrl);
            body = new byte[is.available()];
            is.read(body);
        } else {
            InputStream inStream= OssClient.downloadFile(fileUrl);
            ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
            int rc = 0;
            byte[] buff = new byte[inStream.available()];
            while ((rc = inStream.read(buff, 0, buff.length)) > 0) {
                swapStream.write(buff, 0, rc);
            }
            body = swapStream.toByteArray();
        }
        HttpHeaders headers = new HttpHeaders();
        fileName = new String(fileName.getBytes("utf-8"), "iso-8859-1");
        headers.add("Content-Disposition", "attchement;filename=" + fileName);
        HttpStatus statusCode = HttpStatus.OK;
        ResponseEntity<byte[]> entity = new ResponseEntity<byte[]>(body, headers, statusCode);
        return entity;
    }


}
